package MemcacheTest;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaMD5 {
	private static ThreadLocal<MessageDigest> MD5 = new ThreadLocal<MessageDigest>() {
		protected MessageDigest initialValue() {
			try {
				return MessageDigest.getInstance("MD5");
			}
			catch (NoSuchAlgorithmException e) {
				throw new IllegalStateException("++++ no md5 algorythm found");			
			}
		}
	};
	
	public static String byteHEX(byte ib) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] ob = new char[2];
		ob[0] = Digit[(ib >>> 4) & 0X0F];
		ob[1] = Digit[ib & 0X0F];
		String s = new String(ob);
		return s;
	}
	
	public static String getMD5Str(String str, String charset) {
		try {
			MessageDigest md = MD5.get();
			byte[] data = str.getBytes(charset);
			md.update(data);
			data = md.digest();
			StringBuilder digestHexStr = new StringBuilder(16);
			for (int i = 0; i < 16; i++) {
				digestHexStr.append(byteHEX(data[i]));
			}
			return digestHexStr.toString().toLowerCase();
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}
	
	public static void main(String[] args) {
		System.out.println(getMD5Str("http://g.zhongsou.com/北京创新与激情公司/list/links/23914/1", "utf-8"));
	}
}
